package com.example.family_sec;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.util.SortedList;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.example.family_sec.models.PickInfo;
import com.example.family_sec.models.SecInfo;
import com.example.family_sec.service.MessageService;
import com.example.family_sec.service.ProxyMessage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        MessageService.OnMessageListener {


    private static final int REQ_PER_PHONE_STATE = 302;
    private static final String TAG = MainActivity.class.getSimpleName();
    private MyConnection myConnection = new MyConnection();
    private MessageService.WSBinder wsBinder;
    private SwipeRefreshLayout sw_pull_data;
    private String tel;
    private TextView tv_dd_third;
    private TextView tv_dd_third_tem;
    private TextView tv_dd_third_gas;
    private TextView tv_dd_second;
    private TextView tv_dd_second_tem;
    private TextView tv_dd_second_gas;
    private TextView tv_dd_first;
    private TextView tv_dd_first_tem;
    private TextView tv_dd_first_gas;
    private TextView tv_now_tem;
    private TextView tv_now_gas;
    private TextView tv_now_gas1;
    private TextView tv_now_tem1;
    private TextView tv_pick_time;
    private TextView tv_now_illegal;
    private TextView tv_now_hum;
    private TextView tv_active_refused;


    public MessageService.WSBinder getWsBinder() {
        return wsBinder;
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        SharedPreferences lastLogin = getSharedPreferences("lastLogin", MODE_PRIVATE);

        boolean b = lastLogin.contains("phone") && lastLogin.contains("password");
        if (!b) {
            finish();
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        ImageView iv_weather = findViewById(R.id.iv_weather);

        Glide.with(iv_weather).load(getResources().getDrawable(R.drawable.weather)).into(iv_weather);

        // 连接到服务器
        Intent service = new Intent(this, MessageService.class);

        // 启动服务..
        startService(service);
        // 绑定服务
        bindService(service, myConnection, BIND_AUTO_CREATE);


        //
        sw_pull_data = findViewById(R.id.sw_pull_now_detail);

        // 下拉刷新的设置
        sw_pull_data.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 设置正在拉取数据
                // sw_pull_data.setRefreshing(true);

                ProxyMessage proxyMessage = new ProxyMessage();

                proxyMessage.setCode(ProxyMessage.APP_2_Pr_Detail);
                proxyMessage.setId(23);
                // 获取最新的消息
                proxyMessage.setType(ProxyMessage.APP_2_Pr_Detail);
                proxyMessage.setMsg("test");

                boolean b = wsBinder.sendText(JSON.toJSONString(proxyMessage));
                if (!b) {
                    wsBinder.reConnect();
                }

                sw_pull_data.setRefreshing(false);
            }
        });


        // 当前的
        tv_now_tem = findViewById(R.id.tv_now_tem);
        tv_now_gas = findViewById(R.id.tv_now_gas);

        // 大前天
        tv_dd_third = findViewById(R.id.tv_dd_third);
        tv_dd_third_tem = findViewById(R.id.tv_dd_third_tem);
        tv_dd_third_gas = findViewById(R.id.tv_dd_third_gas);


        // 前天
        tv_dd_second = findViewById(R.id.tv_dd_second);
        tv_dd_second_tem = findViewById(R.id.tv_dd_second_tem);
        tv_dd_second_gas = findViewById(R.id.tv_dd_second_gas);
        //昨天
        tv_dd_first = findViewById(R.id.tv_dd_first);
        tv_dd_first_tem = findViewById(R.id.tv_dd_first_tem);
        tv_dd_first_gas = findViewById(R.id.tv_dd_first_gas);

        // 当前的状况
        tv_now_gas1 = findViewById(R.id.tv_now_gas);
        tv_now_tem1 = findViewById(R.id.tv_now_tem);
        tv_pick_time = findViewById(R.id.tv_pick_time);
        tv_now_illegal = findViewById(R.id.tv_now_illegal);
        tv_now_hum = findViewById(R.id.tv_now_hum);

        tv_active_refused = findViewById(R.id.tv_active_refused);
        tv_active_refused.setTextColor(Color.RED);

        String url = NetUtil.HOST + "/user/pick/info?phone=13123456789&password=12345678";
        NetUtil.pickPass(url, new PickPass());

        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_NUMBERS)) {
            EasyPermissions.requestPermissions(this, "need phone ...", REQ_PER_PHONE_STATE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_NUMBERS);
            return;
        } else {
            //手机号码

            String number = tm.getSimSerialNumber();
            Toast.makeText(this, "number" + number, Toast.LENGTH_SHORT).show();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            tel = tm.getLine1Number();
            Toast.makeText(this, "tel is " + tel, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(myConnection);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQ_PER_PHONE_STATE) {
            // okkk
            TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            String number = tm.getSimSerialNumber();
            tel = tm.getLine1Number();
            System.out.println("number = " + number + " , tel = " + tel.subSequence(3, tel.length()));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

            // startActivity(new Intent(this,SettingActivity.class));
            new SettingFragment().show(getSupportFragmentManager(), "o");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if (id == R.id.nav_quit) {

            // 退出登录.....
            SharedPreferences lastLogin = getSharedPreferences("lastLogin", MODE_PRIVATE);
            SharedPreferences.Editor edit = lastLogin.edit();
            edit.remove("phone");
            edit.remove("password");
            edit.apply();
            this.onRestart();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    // 实现从服务器收到信息的回调接口
    @Override
    public void onMessage(String text) {
        LogUtil.d(TAG, "text = " + text);

        runOnUiThread(() -> {
            sw_pull_data.setRefreshing(false);
            //  Toast.makeText(this, "text = " + text, Toast.LENGTH_SHORT).show();

            ProxyMessage proxyMessage = JSON.parseObject(text, ProxyMessage.class);

            if (proxyMessage == null) {
                return;
            }

            // 如果返回的代码是 404 这个表示服务器积极拒绝和上位相连 ,或者说上位机 根本没有连接成虫
            if (proxyMessage.getCode() == 404){
                runOnUiThread(()->{
                    Toast.makeText(MainActivity.this    , "the hardware active refused ",Toast.LENGTH_SHORT).show();
                    tv_active_refused.setVisibility(View.VISIBLE);
                });
                return ;
            }
            String msg = proxyMessage.getMsg();
            if(msg == null || msg.equals("")){
                return ;
            }
            SecInfo secInfo = JSON.parseObject(msg, SecInfo.class);
            if (secInfo == null) {
                return;
            }



            runOnUiThread(() -> {

                // 设置警报信息不可见
                tv_active_refused.setVisibility(View.INVISIBLE);
                if (sw_pull_data.isRefreshing()) {
                    sw_pull_data.setRefreshing(false);
                }

                //
                // 气体是否要判断手否在正常值....
                // 低温异常
                if (secInfo.getTem() < 18) {
                    tv_now_tem.setText(String.valueOf(secInfo.getTem()) + " °C \n温度过低");

                } else if (secInfo.getTem() > 28) {
                    tv_now_tem.setText(String.valueOf(secInfo.getTem()) + " °C\n温度过高");

                } else {
                    tv_now_tem.setText(String.valueOf(secInfo.getTem()) + " °C\n正常");


                }
                tv_pick_time.setText(TimeFormatUtil.format(new Date()));

                if (secInfo.getGas() == 0) {
                    tv_now_gas1.setText("正常");
                } else {
                    tv_now_gas1.setText("异常..");
                }

                // 设置空外是否正常
                if (0 == secInfo.getIllegal()) {
                    tv_now_illegal.setText("正常");
                    tv_now_illegal.setTextColor(Color.BLACK);
                } else {
                    tv_now_illegal.setText("疑似非法进入");
                    tv_now_illegal.setTextColor(Color.RED);
                }

                // 设置湿度
                tv_now_hum.setText(String.valueOf(secInfo.getHum()));

            });

            if (proxyMessage.getType() == ProxyMessage.RN_4) {
                // todo
            } else if (proxyMessage.getType() == ProxyMessage.RN__3) {

                // 获取 pr的最新消息
            } else if (proxyMessage.getType() == ProxyMessage.Pr_2_APP_DETAIL) {


            }


        });
    }


    class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            wsBinder = (MessageService.WSBinder) service;
            wsBinder.setOnMessageListener(MainActivity.this);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    // 获取最近三天的信息
    class PickPass implements Callback {

        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            byte[] bytes = response.body().bytes();
            response.body().close();

            String text = new String(bytes, 0, bytes.length);

            File file = new File(getExternalFilesDir("info") + "/info.json");
            if (!file.exists()) {
                LogUtil.d(TAG, "no exist ..create");

                file.createNewFile();

                FileOutputStream os = new FileOutputStream(file);

                os.write(bytes);
                os.close();
            } else {
                LogUtil.d(TAG, " exist ..not create");
                FileOutputStream os = new FileOutputStream(file);
                os.write(bytes);
                os.close();
            }

            //   byte [] bs =    byte[] {};
            FileInputStream is = new FileInputStream(file);
            byte[] bs = new byte[]{};
            is.read(bs);
            LogUtil.d(TAG, "read" + new String(bs, 0, bs.length));
            LogUtil.d(TAG, "text" + text);

            //JSON.parseObject(text,PickInfo.class)
            PickInfo pickInfo = JSON.parseObject(text, PickInfo.class);

            if (pickInfo == null || pickInfo.getSecInfo() == null) {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "pull data error ", Toast.LENGTH_SHORT).show();

                });
                return;
            }


            List<SecInfo> secInfos = pickInfo.getSecInfo();
            List<SecInfo> firstInfos = new ArrayList<>();
            List<SecInfo> secondInfos = new ArrayList<>();
            List<SecInfo> thirdInfos = new ArrayList<>();


            if (secInfos != null && secInfos.size() >= 18) {
                firstInfos = secInfos.subList(0, 6);
                secondInfos = secInfos.subList(6, 12);
                thirdInfos = secInfos.subList(12, 18);

                int firstTemLL = 0;
                int firstTemUP = 0;
                int secondTemLL = 0;
                int secondTemUP = 0;
                int thirdTemLL = 0;
                int thirdTemUP = 0;
                firstTemLL = getTemMin(firstInfos);
                firstTemUP = getTemMax(firstInfos);

                secondTemLL = getTemMin(secondInfos);
                secondTemUP = getTemMax(secondInfos);

                thirdTemLL = getTemMin(thirdInfos);
                thirdTemUP = getTemMax(thirdInfos);

                LogUtil.d(TAG, "..........  181818181818 ");

                int finalFirstTemLL = firstTemLL;
                int finalFirstTemUP = firstTemUP;
                int finalSecondTemLL = secondTemLL;
                int finalSecondTemUP = secondTemUP;
                int finalThirdTemLL = thirdTemLL;
                int finalThirdTemUP = thirdTemUP;
                runOnUiThread(() -> {
                    // 更新最近几天的情况
                    tv_dd_first_tem.setText(String.valueOf(finalFirstTemLL) + " ～" + String.valueOf(finalFirstTemUP) + "°c");
                    tv_dd_second_tem.setText(String.valueOf(finalSecondTemLL) + " ～" + String.valueOf(finalSecondTemUP) + "°c");
                    tv_dd_third_tem.setText(String.valueOf(finalThirdTemLL) + " ～" + String.valueOf(finalThirdTemUP) + "°c");
                });
            }
            for (SecInfo m : secInfos) {
                // Log.d(TAG, m.toString());
            }

        }
    }


    // 获取最低温度
    private int getTemMin(List<SecInfo> secInfos) {
        int temp = 0;
        temp = secInfos.get(0).getTem();
        for (SecInfo secInfo : secInfos) {
            if (temp > secInfo.getTem()) {
                temp = secInfo.getTem();
            }
        }

        return temp;
    }

    // 获取最高的温度
    private int getTemMax(List<SecInfo> secInfos) {
        int temp = 0;
        temp = secInfos.get(0).getTem();
        for (SecInfo secInfo : secInfos) {
            if (temp < secInfo.getTem()) {
                temp = secInfo.getTem();
            }
        }

        return temp;
    }
}
